include Java
require 'gookup/common/progressbar'
require 'gookup/gmail/mbox/mbox_handler'
require 'gookup/gmail/model/state_model'
require 'pp'
Killo=1024
READ_ONLY=1
class GmailModel
    include_package('javax.mail')

    attr_writer :store
    attr_reader :mbox_handler

    def initialize
        @state=StateModel.new
        @mbox_handler = MboxHandler.new(Settings.inbox)
    end

    def fetch_inbox_data
        @inbox = @store.getFolder("INBOX")
        @inbox.open(READ_ONLY)
    end

    def persist
        verify_last_saved
        total_count=@inbox.messageCount
        left_to_save = (total_count-@state.info[:last_saved])
        puts '# There are '+left_to_save.to_s+' messages to save '
        @pbar = ProgressBar.new("# Gmail", total_count, STDOUT)
        @pbar.set(@state.info.last_saved)

        (@state.info.last_saved+1..total_count).each do |i|
            message=@inbox.message(i)
            begin
                result=@mbox_handler.append_message(message)
            rescue FolderClosedException => e
                puts '# Remote INBOX folder was closed, attempting re-open'
                @inbox.open(READ_ONLY)
                result=@mbox_handler.append_message(message)
            end
            @state.commit(result)
            @pbar.set(i)
        end
    end

    private
    def verify_last_saved
        if (@state.info.last_saved!=0 && @state.info.last_md5!=nil && !@mbox_handler.verify_message(@state.info.last_saved, @state.info.last_md5))
            puts "# Last save message got corrupted & will be re-saved!"
            @mbox_handler.clear_last_message(@state.info.last_size)
            @state.info.total-= @state.info.last_size
            @state.info.last_saved-=1
        end
    end

end
